<template>
  <div class="page">
    <div class="flowchart-area">
      <div class="tree-area">
        <el-tree
          ref="tree"
          node-key="procInstId"
          highlight-current
          class="user-tree"
          :data="groupLists"
          :props="defaultProps"
          @node-click="getTreeNode"
        >
          <div slot-scope="{ data }" class="custom-tree-node flex-row">
            <div class="line-limit">
              {{ data.procInstName }}
            </div>
          </div>
        </el-tree>
      </div>
      <div class="flowchart-area">
        <flowchartSvg
          v-if="showFlow"
          ref="flowchart"
          @saveFlowchart="saveFlowchart"
          @approvalNext="approvalNext"
          @backNode="backNode"
        />
      </div>
    </div>

    <!-- 回退 -->
    <el-dialog title="回退" :visible.sync="backDialogVisible" width="500px">
      <el-form
        :model="backForm"
        :rules="backRules"
        ref="backForm"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="回退节点" prop="backId">
          <el-select v-model="backForm.backId" placeholder="请选择">
            <el-option
              v-for="item in backList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="backDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="backSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import flowchartSvg from '@/views/components/flowchartSvg.vue'
import {
  getProcList,
  saveDeploy,
  getCurProcInstId,
  nextApi,
  getCurFlowchartJson,
  backCurProcInstIdList,
  backCurProcInstId,
  deleteNodeIdList
} from '@/api/model.js'
import mockList from './mockJson.js'

export default {
  name: 'flowchart',
  components: {
    flowchartSvg
  },
  data() {
    return {
      showFlow: false,
      curNode: {},
      defaultkey: [1],
      defaultProps: {
        label: 'procInstName'
      },
      groupLists: [],
      dialogText: '添加模板',
      curProcInstIdArr: [],
      curFlowchartData: {},
      backDialogVisible: false,
      backForm: {
        backId: ''
      },
      backRules: {
        backId: [{ required: true, message: '选择不能为空', trigger: 'change' }]
      },
      backList: []
    }
  },
  methods: {
    // 获取当前实例信息
    getTreeNode(val) {
      this.curNode = val
      this.showFlow = false
      this.getModelInfo(val.procInstId)
    },

    // 获取实例json
    getModelInfo(procInstId) {
      getCurFlowchartJson(procInstId).then(res => {
        this.showFlow = true
        this.curFlowchartData = res
        this.getCurProcInstIdFun().then(result => {
          if (result) {
            this.$nextTick(() => {
              this.$refs.flowchart.updateInitFun(res)
            })
            this.deleteNodeIdListFun()
          }
        })
      })
    },

    // 保存实例
    saveFlowchart(flowchartJson, svgBase64) {
      flowchartJson.documentation = this.curNode.description
      flowchartJson.id = this.curNode.procInstId
      flowchartJson.name = this.curNode.procInstName

      const saveData = {
        description: this.curNode.description || '',
        id: '',
        procInstId: this.curNode.procInstId,
        name: this.curNode.procInstName,
        modelEditorJson: JSON.stringify(flowchartJson)
        // thumbnail: svgBase64
      }
      saveDeploy(saveData).then(() => {
        // if (!type) {
        this.$message.success('保存成功')
        this.deleteNodeIdListFun()
        // this.getModelInfo(this.curNode.procInstId)
        // }
      })
    },

    // 获取当前进行中的节点id
    async getCurProcInstIdFun() {
      let isSuccess = false
      await getCurProcInstId(this.curNode.procInstId).then(res => {
        this.curProcInstIdArr = res || []
        this.$refs.flowchart.initCurIdFun(this.curProcInstIdArr)
        isSuccess = true
      })
      return isSuccess
    },

    // 批转
    approvalNext() {
      this.getCurProcInstIdFun().then(result => {
        if (result) {
          if (this.curProcInstIdArr && this.curProcInstIdArr.length < 1) {
            this.$message.error('没有正在进行的节点')
            return
          }
          const postData = {
            procInstId: this.curNode.procInstId,
            actId: this.curProcInstIdArr && this.curProcInstIdArr[0]
          }
          nextApi(postData).then(() => {
            this.showFlow = false
            this.$message.success('批转成功')
            // this.nodeFinishied()
            this.getModelInfo(this.curNode.procInstId)
          })
        }
      })
    },

    // 完成节点打钩
    nodeFinishied() {
      this.showFlow = true
      const userTasksArr = this.curFlowchartData.userTasks.map(q => {
        if (q.id === this.curProcInstIdArr[0]) {
          q.finished = true
        }
        return q
      })
      this.curFlowchartData.userTasks = userTasksArr
      this.$nextTick(() => {
        // 渲染流程并自动保存
        this.$refs.flowchart.updateInitFun(this.curFlowchartData, 100)
      })
    },

    // 回退列表
    backNode() {
      this.backForm.backId = ''
      this.backDialogVisible = true
      const obj = {
        modelId: this.curNode.modelId,
        procInstId: this.curNode.procInstId,
        currentTaskDefKey: this.curProcInstIdArr[0]
      }
      backCurProcInstIdList(obj).then(res => {
        this.backList = res
      })
    },

    // 回退提交
    backSubmit() {
      this.$refs.backForm.validate(valid => {
        if (valid) {
          const obj = {
            modelId: this.curNode.modelId,
            procInstId: this.curNode.procInstId,
            currentTaskDefKey: this.curProcInstIdArr[0],
            targetTaskDefKey: this.backForm.backId
          }
          backCurProcInstId(obj).then(() => {
            this.$message.success('回退成功')
            this.backDialogVisible = false
            this.getModelInfo(this.curNode.procInstId)
          })
        }
      })
    },

    // 获取可减签id列表
    deleteNodeIdListFun() {
      const obj = {
        modelId: this.curNode.modelId,
        procInstId: this.curNode.procInstId
      }
      deleteNodeIdList(obj).then(res => {
        const idArr = res.map(q => {
          return q.id
        })
        this.$refs.flowchart.deleteNodeIdListInit(idArr)
      })
    },

    // 默认实例显示
    initMenuList(id) {
      getProcList(this.modelKey || localStorage.getItem('modelKey')).then(
        res => {
          this.groupLists = res
          this.curNode = this.groupLists[0]
          if (res && res.length < 1) return
          this.getModelInfo(this.groupLists[0].procInstId)
          this.$nextTick(() => {
            this.$refs['tree'].setCurrentKey(
              this.groupLists && this.groupLists[0].procInstId
            )
          })
        }
      )
    }
  },
  created() {
    this.modelKey = this.$route.params && this.$route.params.modelKey
    if (this.modelKey) {
      localStorage.setItem('modelKey', this.modelKey)
    }
    this.initMenuList()
  }
}
</script>

<style lang="less" scoped>
.pointer {
  cursor: pointer;
}
.page {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.flowchart-area {
  display: flex;
}
.tree-area {
  width: 240px;
  border-right: solid 1px #dcdcdc;

  .menu-list {
    margin: 10px;
    border-bottom: solid 1px #dcdcdc;
    i {
      padding: 8px;
    }
  }
}
.flowchart-area {
  width: calc(100%);
  height: 100%;
}
::v-deep .el-tree-node__content {
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  padding-left: 2px;
}
::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  padding: 0;
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.line-limit {
  width: 220px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
::v-deep .el-select {
  width: 100%;
}
</style>
